package planner.goals;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import org.jdom.Document;
import org.jdom.Element;
import org.jdom.input.SAXBuilder;

public class ActivityLoader {
	
	private ArrayList<Activity> activities;
	private Iterator<Activity> iActivities;
	private final boolean debug = false;
	private String nextGoalName;
	
	public ActivityLoader(String fileName){
		activities = new ArrayList<Activity>();
		loadGoals(fileName);
		printActivitiesLoaded();
		iActivities = activities.iterator();
	}	
	
	private void loadGoals(String fileName){
		SAXBuilder builder = new SAXBuilder();
		try {
			Document doc = builder.build(fileName);			
			Element root = doc.getRootElement();			
			
			if(root.getAttributeValue("name") != null){				
				loadActivity(root);
			} else {
				List allElements = root.getChildren();			
				Iterator it = allElements.iterator();
	
				while(it.hasNext()){
					Element entry = (Element)it.next();
					loadActivity(entry);
				}				
			} 
			iActivities = activities.iterator();
			
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}		
	}
	
	
	private void loadActivity(Element entry){
		Activity newAct = new Activity(entry.getAttributeValue("name"));
		
		List attrList = entry.getChildren("goal");
		Iterator iAttr = attrList.iterator();
		
		while (iAttr.hasNext()) {
			Element attr = (Element) iAttr.next();
			newAct.addGoal(attr.getValue());
		}				
		activities.add(newAct);		
	}
	
	public Activity getNextActivity(){
		
		Activity nextCase = iActivities.next();
		nextCase.initSequence();
		
		return nextCase;
	}
	
	public boolean hasNextActivity(){
		return iActivities.hasNext();
	}
	
	private void debug(String txt){
		if(debug)
			System.out.println(txt);
	}
	
	public String getActivityName(){
		return nextGoalName;
	}
	
	private int[] getSubGoalsEntry(String attributeValue) {
		String[] splitted = attributeValue.split("/");
		
		int entries[] = new int[splitted.length - 1]; 
		
		for(int i = 1; i < splitted.length; i++)
			entries[i - 1] = Integer.valueOf(splitted[i].trim());
		
		return entries;
	}
	
	private void printActivitiesLoaded(){
		if(debug){
			Iterator<Activity> iAc = activities.iterator();
			
			while (iAc.hasNext()) {
				Activity activity = (Activity) iAc.next();
				activity.printActivity();
			}			
		}
	}
}
